package org.tamal.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.tamal.Session;
import org.tamal.model.User;
import org.tamal.validator.UserValidator;

/**
 * This controller will authenticate users.
 * @author Tamal Kanti Nath
 */
@Controller
public final class Login {

    private final String view = "login";
    private final Logger log = Logger.getLogger(getClass().getName());

    /**
     * Initialize Web Data Binder.
     * @param binder the Web Data Binder
     */
    @InitBinder
    public static void initBinder(WebDataBinder binder) {
        binder.setValidator(new UserValidator());
    }

    /**
     * This method represents a welcome screen.
     * @param model the model
     * @return the view name
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String welcome(Model model) {
        model.addAttribute(new User());
        return view;
    }

    /**
     * This method represents a welcome screen.
     * @param session the HTTP Session
     * @return the view name
     */
    @RequestMapping("/logout")
    public static String logout(HttpSession session) {
        session.removeAttribute(Session.USER.name());
        return "redirect:/";
    }

    /**
     * This method will validate the user.
     * @param user the model attribute
     * @param result the binding result
     * @param session the HTTP session
     * @return the view name
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Valid @ModelAttribute User user, BindingResult result,
            HttpSession session) {
        if (result.hasErrors()) {
            return view;
        }
        session.setAttribute(Session.USER.name(), user.getUserName());
        log.debug("User " + user.getUserName() + " is logged in");
        Object redirect = session.getAttribute(Session.FORWARD.name());
        session.removeAttribute(Session.FORWARD.name());
        return "redirect:" + redirect;
    }
}
